package com.fj.netty.chat.handler;

import com.fj.netty.chat.message.GroupChatResponseMessage;
import com.fj.netty.chat.message.GroupQuitRequestMessage;
import com.fj.netty.chat.server.service.GroupSession;
import com.fj.netty.chat.server.service.ServiceFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.Set;

/**
 * @author fj
 * @date 2024/1/12 16:29
 */
@Slf4j
public class GroupQuitRequestMessageHandler extends SimpleChannelInboundHandler<GroupQuitRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupQuitRequestMessage msg) throws Exception {
        GroupSession groupSession = ServiceFactory.getGroupSession();
        ServiceFactory.getGroupSession().quit(msg.getUsername(), msg.getGroupName());
        Set<Channel> channels = groupSession.memberChannels(msg.getGroupName());
        for (Channel channel:channels){
            GroupChatResponseMessage groupChatResponseMessage = new GroupChatResponseMessage();
            groupChatResponseMessage.setFrom("系统消息");
            groupChatResponseMessage.setContent(msg.getUsername()+"退出群聊"+msg.getGroupName());
            channel.writeAndFlush(groupChatResponseMessage);
        }
    }
}
